package com.example.demo.component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import com.example.demo.util.JsonUtil;

/**
 * 服务启动初期处理
 * **/
@Component
@Order(1)
public class CommandLineRunnerX  implements CommandLineRunner {
	
	private static final Logger logger = LogManager.getLogger(CommandLineRunnerX.class);
	
	@Value("classpath:config/data/admin.json")
	private Resource adminResource;
	
	@Override
    public void run(String... args) throws Exception {
        try {
        	logger.info("Load resource: " + adminResource);
        	String adminRes = this.readString(adminResource);
			@SuppressWarnings("unchecked")
			List<Map<String, String>> adminList = (List<Map<String, String>>)JsonUtil.parseArray(adminRes, ArrayList.class);
			int i = -1;
        	for(Map<String, String> m : adminList) {
        		logger.info("Load resource" + i + ":" + m.entrySet());
        	}
        }catch(Exception e) {
        	e.printStackTrace();
        	logger.error(e.getMessage());
        }
    }
	
	// 读取文件
	public String readString(Resource resource) {
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(resource.getInputStream(), "UTF-8"));
            StringBuilder content = new StringBuilder();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                content.append(line);
            }
            return content.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}
